package com.chenchao.thread;

import java.util.HashMap;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/18 9:54
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javathread.Thead17.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 造成死锁
 */
public class Test17 implements Runnable{
    private static HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
    private static String m1="镜子";
    private static String m2="梳子";
    public static void main(String[] args) throws InterruptedException {
        init();
        Thread thread1 = new Thread(new Test17(), "龟太公");
        Thread thread2 = new Thread(new Test17(), "姜子牙");
        thread1.start();
        Thread.sleep(1000);//防止thread2读取错误的stringIntegerHashMap信息
        thread2.start();

    }
    @Override
    public void run() {
        if(stringIntegerHashMap.get("镜子")==1){
            synchronized (m1){
                System.out.println(Thread.currentThread().getName()+"获得了镜子");
                stringIntegerHashMap.put("镜子",0);//取出镜子
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (m2){
                    System.out.println(Thread.currentThread().getName()+"获得了梳子");
                }
            }
        }
        else {
            synchronized (m2){
                System.out.println(Thread.currentThread().getName()+"获得了梳子");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (m1){
                    System.out.println(Thread.currentThread().getName()+"获得了镜子");
                }
            }
        }

    }
    public static void init(){
        stringIntegerHashMap.put("镜子",1);
        stringIntegerHashMap.put("梳子",1);
    }
}
